<script setup>
import { useRouter } from 'vue-router';
import { ref, reactive, onMounted, toRaw } from 'vue'
import { useStore } from 'vuex'
import moment from 'moment'
import { ElMessage } from 'element-plus'
import request from '@/utils/request'
import { userSubmit, getUserList, deleteUser, getRoleList, getDeptList, getPermissionList } from '@/api/index'

getPermissionList()

const tableDom = ref()
const createUser = ref()
const state = reactive({
  form: {
    userName: '',
    userId: '',
    state: 0,
  },
  isShowCreateUser: false,
  userList: [],
  roleList: [],
  action: 'add',
  deptList: [],
  selectionUsers: [],
  pageer: {
    pageNum: 1,
    pageSize: 10,
    total: 0,
  }
})
const roleListOptions = ref([])
const userForm = reactive({
  state: 3
})
const userRules = {
  userName: [
    { required: true, message: '请输入账号', trigger: 'blur' },
    { min: 1, max: 32, message: '账号最少8位, 最长32位', trigger: 'blur' },
  ],
  userEmail: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
  ],
  mobile: [
    { pattern: /^1\d{10}$/, message: '请输入正确的手机号', trigger: 'change' }
  ],
  deptId: [
    { required: true, message: '请选择部门', trigger: 'blur' },
  ],
  // roleList: [
  //   { required: true, message: '请选择系统角色', trigger: 'blur' },
  // ],
}
const roleMap = {
  0: '管理员',
  1: '普通用户'
}
const stateMap = {
  1: '在职',
  2: '离职',
  3: '试用期'
}
const columns = reactive([
  { label: '用户ID', prop: 'userId', },
  { label: '用户名称', prop: 'userName', },
  { label: '用户邮箱', prop: 'userEmail', width: 200 },
  {
    label: '用户角色', prop: 'role', formatter: (row, column, value) => {
      return roleMap[value] || roleMap[1]
    },
    width: 90
  },
  {
    label: '用户状态', prop: 'state', formatter: (row, column, value) => {
      return stateMap[value] || stateMap[1]
    },
    width: 80
  },
  {
    label: '注册时间', prop: 'createTime', formatter: (row, column, value) => {
      return moment(value).format('YYYY-MM-DD HH:mm');
    }
  },
  {
    label: '最后登录时间', prop: 'lastLoginTime', formatter: (row, column, value) => {
      return moment(value).format('YYYY-MM-DD HH:mm')
    }
  },
])

onMounted(async () => {
  query()
  initRoleList()
  initDeptList()
})

const query = async () => {
  try {
    const params = {
      ...state.form,
      ...state.pageer
    }
    let { list, page } = await getUserList(params);
    state.userList = list
    state.pageer = page
  } catch (error) {
    console.error(error)
  }
}

const handelReset = () => {
  state.form = {
    userName: '',
    userId: '',
    state: 0,
  }
  state.pageer = {
    pageNum: 1,
    pageSize: 10,
    total: 0,
  }
}
const handelQuery = () => {
  query()
}

const handelCurrentChange = (currentPage) => {
  state.pageer.pageNum = currentPage
  query()
}

const delUser = async (ids) => {
  try {
    await deleteUser({
      userIds: ids,
    })
    ElMessage({
      message: '删除成功',
      type: 'success'
    })
    query();
  } catch (error) {
    console.error(error);
  }
}

const handelPatchDel = async () => {
  if (state.selectionUsers.length) {
    delUser(state.selectionUsers)
  }
}

const handelSelectionUsers = (users) => {
  state.selectionUsers = users.map(item => item._id)
}
const handelCreateUser = () => {
  createUser.value.validate(async (valid, fields) => {
    if (valid) {
      let data = toRaw(userForm)
      data.action = state.action
      let res = await userSubmit(data)
      ElMessage({
        message: state.action === 'add' ? '添加成功' : '修改成功',
        type: 'success'
      })
      state.isShowCreateUser = false
      await query()
    } else {
      console.log('验证不通过')
    }
  })
}
const handelCloseCreateUser = () => {
  state.isShowCreateUser = false
}

const initDeptList = async () => {
  try {
    let res = await getDeptList()
    state.deptList = res;
  } catch (error) {
    console.error(error)
  }
}

const initRoleList = async () => {
  try {
    let res = await getRoleList()
    state.roleList = res;
  } catch (error) {
    console.error(error)
  }
}

const handelEdit = (row) => {
  state.isShowCreateUser = true
  state.action = 'edit'
  Object.assign(userForm, row)
}

const resetUserForm = () => {
  createUser.value.resetFields()
}

</script>
<template>
  <div class="user-manger">
    <div class="query-form">

      <el-form :inline="true" :model="state.form">
        <el-form-item label="用户ID">
          <el-input v-model="state.form.userId" placeholder="请输入用户ID" />
        </el-form-item>
        <el-form-item label="用户名称">
          <el-input v-model="state.form.userName" placeholder="请输入用户名称" />
        </el-form-item>
        <el-form-item label="用户状态">
          <el-select v-model="state.form.state">
            <el-option :value="0" label="所有"></el-option>
            <el-option :value="1" label="在职"></el-option>
            <el-option :value="2" label="离职"></el-option>
            <el-option :value="3" label="试用期"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handelQuery">查询</el-button>
          <el-button @click="handelReset">重置</el-button>
        </el-form-item>
      </el-form>

    </div>
    <div class="base-table">
      <div class="action">
        <el-button v-has="'user-create'" type="primary" @click="state.isShowCreateUser = true; state.action = 'add'">新增</el-button>
        <el-button v-has="'user-patch-delete'" type="danger" @click="handelPatchDel">批量删除</el-button>
      </div>
      <el-table @selection-change="handelSelectionUsers" ref="tableDom" :data="state.userList" style="width: 100%">
        <el-table-column type="selection" width="55" />
        <el-table-column v-for="item of columns" :key="item.prop" :prop="item.prop" :formatter="item.formatter" :label="item.label"
          :width="item.width" />
        <el-table-column align="right" width="150">
          <template #default="scope">
            <el-button v-has="'user-edit'" type="primary" @click="handelEdit(scope.row)">编辑</el-button>
            <el-button v-has="'user-delete'" type="danger" @click="delUser([scope.row._id])">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination @current-change="handelCurrentChange" class="pagination" background layout="prev, pager, next"
        :page-size="state.pageer.pageSize" :total="state.pageer.total" />
    </div>
    <el-dialog title="新增用户" v-model="state.isShowCreateUser" @closed="resetUserForm">
      <el-form :model="userForm" :rules="userRules" ref="createUser" label-width="100">
        <el-form-item label="用户名" prop="userName">
          <el-input v-model="userForm.userName" :disabled="state.action === 'edit'" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item label="用户邮箱" prop="userEmail">
          <el-input v-model="userForm.userEmail" placeholder="请输入用户邮箱">
            <!-- <template #append>
              @gmail.com
            </template> -->
          </el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="userForm.mobile" placeholder="请输入手机号" />
        </el-form-item>
        <el-form-item label="岗位" prop="job">
          <el-input v-model="userForm.job" placeholder="岗位" />
        </el-form-item>
        <el-form-item label="状态" prop="state">
          <el-select v-model="userForm.state">
            <el-option :value="1" label="在职" />
            <el-option :value="2" label="离职" />
            <el-option :value="3" label="试用期" />
          </el-select>
        </el-form-item>
        <el-form-item label="系统角色" prop="roleList">
          <el-select v-model="userForm.roleList" placeholder="请选择角色" multiple :style="{ width: '100%' }">
            <el-option v-for="role of state.roleList" :value="role._id" :label="role.roleName" />
          </el-select>
        </el-form-item>
        <el-form-item label="部门" prop="deptId">
          <el-cascader v-model="userForm.deptId" :options="state.deptList" placeholder='请选择部门'
            :props="{ checkStrictly: true, value: '_id', label: 'deptName' }" clearable :style="{ width: '100%' }" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handelCloseCreateUser">关闭</el-button>
          <el-button type="primary" @click="handelCreateUser">
            添加
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<style lang="scss"></style>